How Do I Sort Properties?

Quick Tip

To sort properties in alphabetical order of display name, set the PropertyGrid.Sorting property to PropertySorting.ByHumanName:

CopySorting the property grid (declarative)
<ms:PropertyGrid Sorting='{x:Static ms:PropertySorting.ByHumanName}'/>

In Depth

Sorting in WPF is done through collection views. The collection view for the WPF Property Grid is the default view of the PropertyGrid.BindingView collection. Setting the Sorting property as shown above is a shortcut for setting the CustomSort property of this collection view to the PropertySorting.ByHumanName IComparer. (CustomSort is a property of ListCollectionView; if you want to set it directly on the collection view you will need to cast it.)

You can also perform sorting by modifying the SortDescriptions collection of PropertyGrid.BindingView.DefaultView. This avoids having to implement an IComparer but is limited to simple ascending and descending sorts on individual properties.

For more information see the articles Sorting and grouping in the WPF Property Grid and Custom sorting WPF collection views and the WPF Property Grid on the Mindscape blog.

Custom Sorting and ItemsSource Dictionaries

The same techniques apply if you are populating the grid from an ItemsSource dictionary rather than a SelectedObject. However, sometimes you need to sort on something other than the display name and value. For example, suppose you are displaying a dictionary of aristocrats and their incomes. Because aristocrats are very sensitive, you want to sort the grid in order of precedence rather than by name or by income.

The solution is to create a custom key type which contains the additional data required for sorting, but which still renders as the name when displayed. In this example, you could create an AristocratInfo class with Name and Precedence properties. Implement ToString() on this class to return the name, and implement IComparable<AristocratInfo> to sort by precedence. Then set ItemsSource to a Dictionary<AristocratInfo, decimal> instead of a Dictionary<string, decimal>.

If you want to offer multiple sort orders on a “smart dictionary,” you can still do so by setting the PropertyGrid.Sorting property or the SortDescriptions collection. The dictionary key is available as Node.IndexedPropertyArguments[0], so your sort expressions can refer to Node.IndexedPropertyArguments[0].Name and Node.IndexedPropertyArguments[0].Precedence.